//
//  UIImageView+Loader.m
//  ImageLoader
//
//  Created by Le Ngoc Thanh on 8/23/13.
//  Copyright (c) 2013 Le Ngoc Thanh. All rights reserved.
//

#import "UIImageView+Loader.h"
#import "UIImage+Loader.h"
#import "HMImageDownloadManager.h"

@implementation UIImageView (Loader)
- (void)loadImageFromUrl:(NSString *)url imagePlaceHolder:(UIImage *)placeHolderImage{
    UIImage *image = [UIImage imageLocalFromOnlineUrl:url];
    if (!image) {
        image = placeHolderImage;
        [[HMImageDownloadManager share] downloadUrl:url complete:nil errorHandler:nil priority:TYPELOAD_HIGHTPRIORITY canOverride:NO];
        [self regisNotification:url];
    }
    [self setImage:image];
}
- (void)loadImageFromUrl:(NSString *)url imagePlaceHolder:(UIImage *)placeHolderImage isOverride:(BOOL)override{
    UIImage *image = [UIImage imageLocalFromOnlineUrl:url];
    if (!image) {
        image = placeHolderImage;
        [[HMImageDownloadManager share] downloadUrl:url complete:nil errorHandler:nil priority:TYPELOAD_HIGHTPRIORITY canOverride:override];
        [self regisNotification:url];
    }
    [self setImage:image];
}
- (void)loadImageFromUrl:(NSString *)url local:(NSString *)local imagePlaceHolder:(UIImage *)placeHolderImage{
    UIImage *image = [UIImage imageLocalFromOnlineUrl:url];
    if (!image) {
        image = placeHolderImage;
        [[HMImageDownloadManager share] downloadUrl:url local:local complete:nil errorHandler:nil priority:TYPELOAD_HIGHTPRIORITY canOverride:NO];
        [self regisNotification:url];
    }
    [self setImage:image];
}

- (void)regisNotification:(NSString *)url{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiverImage:) name:url object:nil];
}
- (void)receiverImage:(NSNotification *)noti{
    UIImage *image = [UIImage imageLocalFromOnlineUrl:noti.object];
    if (image) {
        [self setImage:image];
    }
}
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
